<template>
    <view class="container" v-if="show">
        <view class="top-buttons">
            <view  class="top-btn">
                <view @click="close"><uni-icons type="closeempty" size="30"></uni-icons></view>
            </view>
            <view  class="top-btn">
                <view ><uni-icons type="undo-filled" size="30" v-if="redoStack.length>1" @click="lastStep"></uni-icons><uni-icons type="undo" size="30" v-else></uni-icons></view>
                <view ><uni-icons type="redo-filled" size="30" v-if="undoStack.length>0" @click="nextStep"></uni-icons><uni-icons type="redo" size="30" v-else></uni-icons></view>
            </view>
        </view>
        <view class="canvas-wrap">
            <canvas type="2d" canvas-id="canvas" id="canvas" class="canvas" disable-scroll="true" @touchstart="touchstart"
                @touchmove="touchmove" @touchend="touchend" @longtap="longpress"></canvas>
        </view>
        <view class="colors">
            <view v-if="globalData.isPC" style="max-width: 300rpx;display:flex;min-width:50%;justify-content: space-evenly;">
                <view 
                v-for="(color, index) in colors" 
                :key="index"
                class="color-item" 
                :style="{background: color.value, border: color.selected ? '2px solid #dada00' : '1px solid #000'}"
                @click="selectColor(index)"
                ></view>
            </view>
            <view v-else style="display:flex;width:80%;justify-content: space-evenly;">
                <view 
                v-for="(color, index) in colors" 
                :key="index"
                class="color-item" 
                :style="{background: color.value, border: color.selected ? '2px solid #dada00' : '1px solid #000'}"
                @click="selectColor(index)"
                ></view>
            </view>
            <view style="flex:1;text-align: center;" v-if="globalData.isPC">
                <text style="font-size: 24rpx;">画布大小</text>
                <view style="flex:1;">
                    <slider :value="scale" activeColor="#d88303" block-color="#d88303" :show-value="true" block-size="20" step="0.2" min="0.4" max="2" @change="changeScale"></slider>
                </view>
            </view>
        </view>
        
        <view class="buttons">
            <view class="slide">
                <slider :value="fontSize" block-color="#4cd964" :show-value="true" block-size="20" step="1" min="12" max="35" @change="changeFontSize"></slider>
            </view>
            <!-- 文字功能 -->
            <view class="item" @click="addText" :disabled="isDrawing" style="font-size: 44rpx;"> 𝚃 </view>
            <!-- 涂鸦功能 -->
            <view class="item" @click="addDiyLine"><uni-icons type="compose" color="#4cd964" size="22" v-if="isDrawing"></uni-icons> <uni-icons type="compose" size="22" v-else></uni-icons> </view>
            <!-- 旋转功能 -->
            <view class="item" @click="rotate" :disabled="isDrawing"><uni-icons type="loop" size="22"></uni-icons></view>
            <view class="item" @click="clear"><uni-icons type="trash" size="22"></uni-icons></view>
            <view class="item save" @click="saveImage">发送</view>
        </view>
    </view>
</template>
<script>
    import {
        CanvasDraw
    } from '../../common/js/CanvasDraw.js'
    var app = getApp()
    var canvasDraw = null, // 绘图对象
        canvasEle = null, // canvas元素对象
        imgs = {
            star: '../../static/img/file.png',
            delete: '../../../static/delete.png',
        },
        startPoint = null, // 手绘起点
        createId = null, // 手绘id
        longpressPoint=null,//长按点
        fingers = 1, // 手指数量
        fillColor='rgba(0,255,0)',//选框填充色
        selectedFillcolor='rgba(255,0,0)'//选中的选框色
        
    let getImageInfo = function(src) {
        return new Promise((resolve, reject) => {
            wx.getImageInfo({
                src: src,
                success: res => {
                    console.log('aaa', res)
                    resolve(res)
                },
                fail: res => reject(res)
            });
        });
    };
    export default {
        data() {
            return {
                show: false,
                imgSrc: '',
                scale:1,
                globalData: "",
                isDrawing: false, // 是否正在绘图
                fontSize:20,
                colors: [
                  { value: 'rgba(0,0,0)', selected: true },
                  { value: 'rgba(255,255,255)', selected: false },
                  { value: 'rgba(0,0,255)', selected: false },
                  { value: 'rgba(197,174,9)', selected: false },
                  { value: 'rgba(255,0,0)', selected: false },
                  { value: 'rgba(255,0,255)', selected: false }
                ],
                fillColor: 'rgba(0,0,0)',
                undoStack: [], // 撤销栈
                redoStack: [], // 重做栈
                groupId:1,//当前组id，记录第几次添加内容
            }
        },

        created() {},
        beforeDestroy() {
            /** 销毁对象 */
            if (canvasDraw) {
                canvasDraw.destroy()
                canvasDraw = null
            }
        },
        onLoad() {
            this.globalData = app.globalData
        },
        onShow() {
        },
        mounted() {
            /** 初始化 */
            // this.addImage('a',0,0,400,600)
            setTimeout(() => {
                // this.initCanvas()
                // this.addImagePoint(0,0)
                
                console.log('globalData', app.globalData)
                this.globalData = app.globalData
            }, 100)
        },
        methods: {
            changeFontSize(e){
                console.log('changeFontSize',e)
                this.fontSize = e.detail.value
            },
            changeScale(e){
                this.scale = e.detail.value
                canvasDraw.zoomTo(this.scale)
            },
            open(options = {}) {
                this.show = true
                this.imgSrc = options.imgSrc || this.imgSrc
                this.$nextTick(() => {
                    this.initCanvas()
                    setTimeout(() => {
                        this.addImagePoint(0,0)
                    }, 300)
                })
            },
            close() {
                this.show = false
                this.$emit('close')
            },
            saveImage() {
                this.isDrawing = false
                this.convertCanvasToImage()
                this.close()
            },
            selectColor(index) {
                this.colors.forEach((color, i) => {
                  color.selected = i === index;
                });
                this.fillColor = this.colors[index].value;
              },
            /** 初始化canvas */
            initCanvas(width, height) {
                const query = wx.createSelectorQuery().in(this)
                    query
                    .select('#canvas')
                    .fields({
                        node: true,
                        size: true,
                        rect: true
                    })
                    .exec((res) => {
                        const ele = res[0]
                        canvasEle = ele

                        // 配置项
                        const option = {
                            ele: canvasEle, // canvas元素
                            drawCallBack: this.draw, // 必须：用户自定义绘图方法
                            scale: this.scale, // 当前缩放倍数
                            scaleStep: 0.1, // 缩放步长（按钮)
                            touchScaleStep: 0.005, // 缩放步长（手势）
                            maxScale: 2, // 缩放最大倍数（缩放比率倍数）
                            minScale: 0.5, // 缩放最小倍数（缩放比率倍数）
                            // width: img.width, // 画布宽度
                            // height: img.height, // 画布高度
                            translate: {
                                x: 0,
                                y: 0
                            }, // 默认画布偏移
                            isThrottleDraw: true, // 是否开启节流绘图（建议开启，否则安卓调用频繁导致卡顿）
                            throttleInterval: 20, // 节流绘图间隔，单位ms
                            pixelRatio: wx.getSystemInfoSync().pixelRatio, // 像素比（高像素比可以解决高清屏幕模糊问题）
                            controls: {
                                delete: {
                                    radius: 20,
                                    fill: fillColor,
                                    customDraw: this.drawDeleteControl,
                                },
                            },
                        }
                        canvasDraw = new CanvasDraw(option) // 创建CanvasDraw实例后就可以使用实例的所有方法了
                        this.addEvents() // 添加事件监听
                        canvasDraw.draw() // 可以按实际需要调用绘图方法
                        this.redoStack = canvasDraw.children
                        console.log('canvasDraw', canvasDraw)
                    })
                
            },

            /** 绑定组件内置事件 */
            addEvents() {
                canvasDraw.on('selection:updated', this.onSelectionUpdated)
                canvasDraw.on('selection:cleared', this.onSelectionCleared)
                canvasDraw.on('touchstart', this.onTouchstart)
                canvasDraw.on('touchmove', this.onTouchmove)
                canvasDraw.on('touchend', this.onTouchend)
                canvasDraw.on('tap', this.onTap)
                canvasDraw.on('deleteControl:tap', this.onDeleteControl)
                canvasDraw.on('longtap',this.onLongpress)
            },

            /** 用户自定义绘图内容 */
            draw() {
                // 1.默认绘图方式-圆形
                // const { ctx } = canvasDraw
                // ctx.beginPath()
                // ctx.strokeStyle = '#000'
                // ctx.arc(50, 50, 50, 0, 2 * Math.PI)
                // ctx.stroke()
                // ctx.closePath()
            },

            /** 中心放大 */
            zoomIn() {
                canvasDraw.zoomIn()
            },

            /** 中心缩小 */
            zoomOut() {
                canvasDraw.zoomOut()
            },

            /** 重置画布（回复初始效果） */
            reset() {
                canvasDraw.reset()
            },

            /** 清空画布 */
            clear() {
                console.log('this.redoStack',canvasDraw.children)
                canvasDraw.clear()
                //清空后要把图片绘制上去
                this.addImagePoint(0,0)
                this.redoStack = canvasDraw.children
            },
            
            /** 旋转功能 */
            rotate() {
                canvasDraw.rotateCanvas(90) // 逆时针旋转90度
            },
            /** 组件方法-绘制多边形 */
            addShape() {
                const opt = {
                    points: [{
                            x: 148,
                            y: 194
                        },
                        {
                            x: 196,
                            y: 191
                        },
                        {
                            x: 215,
                            y: 244
                        },
                        {
                            x: 125,
                            y: 249
                        },
                    ],
                    style: {
                        strokeWidth: 1,
                        stroke: '#000',
                        lineDash: [2, 2],
                        fill: fillColor
                    },
                }
                canvasDraw.drawShape(opt)
            },

            /** 组件方法-绘制多线段 */
            addLines() {
                const opt = {
                    points: [{
                            x: 53,
                            y: 314
                        },
                        {
                            x: 116,
                            y: 283
                        },
                        {
                            x: 166,
                            y: 314
                        },
                        {
                            x: 224,
                            y: 283
                        },
                        {
                            x: 262,
                            y: 314
                        },
                    ],
                    style: {
                        strokeWidth: 2,
                        stroke: '#000',
                        lineDash: [2, 2]
                    },
                    angle: 45,
                }
                canvasDraw.drawLines(opt)
            },
             /** 组件方法-涂鸦 */
             addDiyLine() {
                this.isDrawing = !this.isDrawing
            },
            /** 组件方法-绘制文字 */
            addText() {
            
                this.onSelectionCleared()
                uni.showModal({
                    title: '添加文字',
                    content: '',
                    editable: true,
                    confirmText:'添加',
                    cancelText:'取消',
                    success: (res) => {
                        let len = res.content.length
                        if(res.confirm){
                            this.groupId++
                            console.log('fontSize',this.fontSize,this.groupId)
                            const opt = {
                                groupId:this.groupId,
                                text: res.content,
                                zIndex:1,
                                points: [{
                                    x: 175 - len*this.fontSize/2,
                                    y: 150
                                },{
                                    x:175+len*this.fontSize/2,
                                    y:150
                                },{
                                    x:175+len*this.fontSize/2,
                                    y:180
                                },{
                                    x:175- len*this.fontSize/2,
                                    y:180
                                }],
                                style: {
                                    fill: '#fff',
                                    color:this.fillColor,
                                    textAlign: 'center',
                                    textBaseline: 'middle',
                                    fontSize:this.fontSize
                                },
                            }
                            canvasDraw.drawText(opt)
                            this.redoStack = canvasDraw.children
                        }
                    }
                })
                
            },

            addImage(img, dx, dy, width, height) {
                let a = getImageInfo(this.imgSrc)
                a.then(res => {
                    //console.log('bbbb', res.height, res.path)
                    imgs.star = res.path
                    const opt = {
                        points: [{
                            x: dx,
                            y: dy
                        }],
                        style: {
                            radius: 40,
                            width: width,
                            height: height
                        },
                        angle: 0
                    }
                    canvasDraw.drawImg(res.path, opt)
                })

            },
            /** 组件方法-绘制点 */
            addPoint() {
                const opt = {
                    points: [{
                        x: 150,
                        y: 50
                    }],
                    style: {
                        radius: 20,
                        strokeWidth: 2,
                        stroke: '#00f',
                        lineDash: [2, 2],
                        fill: '#0f0'
                    },
                }
                canvasDraw.drawPoint(opt)
            },

            /** 组件方法-绘制图片点 */
            addImagePoint(dx, dy) {
                var systemInfo={}
                uni.getSystemInfo({
                	success(res) {
                        systemInfo = res
                    }
                })
                let imgInfo = getImageInfo(this.imgSrc)
                imgInfo.then(res => {
                    let width = systemInfo.windowWidth
                    let height= width/res.width*res.height  //globalData.systemInfo.screenHeight*(750 / globalData.systemInfo.windowWidth)
                    const opt = {
                        zIndex:0,
                        points: [{
                            x: dx,
                            y: dy
                        }],
                        style: {
                            img: this.imgSrc,//res.path,
                            radius: 300,
                            width:width,
                            height:height
                        },
                        angle: 0
                    }
                    console.log('bbbb', dx, dy,opt)
                    canvasDraw.drawAtuoImage(opt)
                    // canvasDraw.drawPoint(opt)
                })
            },

            /** 用户手绘矩形 */
            handDraw() {
                // 如果是手绘则禁止拖拽画布，否则启动拖拽画布
                this.isDrawing = !this.isDrawing
                canvasDraw.canDragCanvas = !this.isDrawing
            },

            /** 组件内置事件 */
            onSelectionUpdated(item) {
                if (this.isDrawing) return
                // console.log('选中元素：', item)
                if(item.type!='AtuoImage'){
                    //原始图片不能删除
                    item.controlsVis = {
                        delete: true
                    } 
                    
                    item.zIndex = 1
                    canvasDraw.draw()
                }
            },
            onSelectionCleared(item) {
                if (this.isDrawing) return
                console.log('取消选中：', item)
                if (!item) return
                item.controlsVis = {
                    delete: false
                }
                item.zIndex = 0
                canvasDraw.draw()
            },
            onTouchstart(e) {
                // console.log('触摸开始：', e)
                startPoint = e.point
                createId = `user_${new Date().getTime()}`
                fingers = e.event.touches.length
            },
            onTouchmove(e) {
                // 如果是绘制状态，触摸移动则进行矩形绘制
                if (fingers !== 1 || !this.isDrawing) return
                const tsPoint = startPoint
                const tmPoint = e.point
                // 两点距离小于5，不进行绘制
                if (Math.abs(tmPoint.x - tsPoint.x) <= 5 || Math.abs(tmPoint.y - tsPoint.y) <= 5) return
                // 先移除，再绘制
                canvasDraw.removeChild(createId)
                canvasDraw.draw()
                //绘制矩形
                // const opt = {
                //     id: createId,
                //     points: [tsPoint, {
                //         x: tmPoint.x,
                //         y: tsPoint.y
                //     }, tmPoint, {
                //         x: tsPoint.x,
                //         y: tmPoint.y
                //     }],
                //     style: {
                //         strokeWidth: 2,
                //         stroke: 'rgba(0,0,0,.2)',
                //         fill: 'rgba(0,255,0,.2)'
                //     },
                // }
                // canvasDraw.drawShape(opt)

                //绘制直线
                // const opt = {
                //     id: createId,
                //     points: [tsPoint, tmPoint],
                //     style: { strokeWidth: 2, stroke: 'rgba(0,0,0,.2)' }
                // }
                // canvasDraw.drawLines(opt)
                //绘制连续的点
                // const opt = {
                //     id: createId,
                //     points: [tsPoint, tmPoint],
                //     style: { strokeWidth: 2, stroke: 'rgba(0,0,0,.2)' }
                // }
                // canvasDraw.drawPoint(opt)
            },
            onTouchend(e) {
                console.log('触摸结束：', e)
                longpressPoint = e.point
                console.log('所有canvas子对象：', canvasDraw.children)
            },
            onTap(e) {
                console.log('点击坐标：', e.point)
                console.log('所有canvas子对象：', canvasDraw.children)
            },
            onDeleteControl(e) {
                console.log('点击删除控制点', e)
                canvasDraw.removeChild(e.id)
                canvasDraw.draw()
            },
            
            /** 上一步 */
            lastStep() {
                let hasElements = false
                const currentGroupElements = canvasDraw.children.filter(item => item.groupId === this.groupId)
                
                if (currentGroupElements.length > 0) {
                    canvasDraw.children = canvasDraw.children.filter(item => item.groupId !== this.groupId)
                    this.undoStack.push(...currentGroupElements)
                    hasElements = true
                }

                if (!hasElements && this.groupId > 1) {
                    this.groupId--
                    this.lastStep()
                } else if (hasElements) {
                    // 成功撤销后，将当前组号减1以便下次操作
                    this.groupId = Math.max(1, this.groupId - 1)
                }
                console.log('this.groupId',this.groupId)
                canvasDraw.draw()
            },
            
            /** 下一步 */
            nextStep() {
                if (this.undoStack.length > 0) {
                    // 先递增组号再查找
                    this.groupId++
                    const currentGroupEmpty = !canvasDraw.children.some(item => item.groupId === this.groupId)
                    
                    if (currentGroupEmpty) {
                        const restoreElements = this.undoStack.filter(item => item.groupId === this.groupId)
                        if (restoreElements.length > 0) {
                            canvasDraw.children.push(...restoreElements)
                            this.undoStack = this.undoStack.filter(item => item.groupId !== this.groupId)
                        } else {
                            // 没有找到对应组元素，回退组号
                            this.groupId--
                        }
                    } else {
                        // 当前组已有内容，需要继续前进
                        this.groupId++
                    }
                    
                    console.log('this.groupId',this.groupId)
                    canvasDraw.draw()
                }
            },
            // 自定义绘制删除控制点
            drawDeleteControl(opt) {
                canvasDraw.drawPoint({
                        id: 'delete',
                        points: opt.points,
                        style: {
                            img: imgs.delete,
                            radius: 20,
                            width:14,
                            height:14
                        },
                    },
                    true
                )
            },

            /** canvas事件绑定 */
            touchstart(e) {
                console.log('touchstart',e)
                this.groupId++
                canvasDraw.touchstart(e)
            },
            touchmove(e) {
                if (this.isDrawing) {
                    // 绘制点
                    const point = e.touches[0];
                    // 考虑画布偏移量
                    const adjustedX = (point.x - canvasDraw.translate.x) / canvasDraw.scale;
                    const adjustedY = (point.y - canvasDraw.translate.y) / canvasDraw.scale;
                    const opt = {
                        groupId:this.groupId,
                        isDrawing: true,
                        id: `point_${new Date().getTime()}`,
                        zIndex:2,
                        points: [{x: adjustedX, y: adjustedY}],
                        style: { 
                            strokeWidth: 2, 
                            stroke: this.fillColor,
                            radius: 2,
                            fill:this.fillColor
                        }
                    };
                    canvasDraw.drawPoint(opt,true);
                }else{
                    // 移动画布
                    // console.log('移动画布',e)
                    canvasDraw.touchmove(e);

                }
            },
            touchend(e) {
                canvasDraw.touchend(e)
                this.redoStack = canvasDraw.children
            },
            longpress(e) {
                console.log('longpress',e)
                canvasDraw.longtap(e)
            },
            // 新增转换方法
            convertCanvasToImage() {
                canvasDraw.draw(); // 确保所有元素已绘制
                canvasDraw.exportAsImage((tempFilePath) => {
                    console.log('tempFilePath',tempFilePath)
                    this.$emit('returnImg',tempFilePath)
                    // uni.saveImageToPhotosAlbum({
                    //     filePath: tempFilePath,
                    //     success: () => {
                    //         uni.showToast({ title: '保存成功' });
                    //     },
                    //     fail: (err) => {
                    //         if (err.errMsg.includes('auth')) {
                    //             uni.showModal({
                    //                 title: '提示',
                    //                 content: '需要相册权限',
                    //                 success: (res) => {
                    //                     if (res.confirm) {
                    //                         uni.openSetting();
                    //                     }
                    //                 }
                    //             });
                    //         } else {
                    //             uni.showToast({ title: '保存失败', icon: 'none' });
                    //         }
                    //     }
                    // });
                });
            },
        },
    }
</script>
<style lang="scss" scoped>
    page {
        background: #f2f2f2;
        height: 100vh;
        overflow: hidden;
        display: flex;
    }

    .container {
        display: flex;
        flex: 1;
        flex-direction: column;
        height: 100%;
        position: fixed;
        top:0;
        left: 0;
        width: 100vw;
        height: 100vh;
        background-color: #fff;
        z-index: 999999;
    }

    .canvas-wrap {
        display: flex;
        margin: 10px;
        height: 76vh;
    }

    .canvas {
        flex: 1;
        width: 100%;
        height: 100%;
        background: #fff;
    }
    .top-buttons{
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin: 0 10px;
        .top-btn{
            display: flex;
            view{
                margin: 0 20rpx;
                font-size: 24rpx;
                padding: 4rpx 10rpx;
            }
        }
    }
    .buttons {
        display: flex;
        justify-content: center;
        align-items: center;
        margin: 0 10px;
        z-index: 11111;
        .slide{
            flex:1
        }
        .item{
            padding: 10rpx 15rpx;
            margin: 0 10rpx;
        }
        .save{
            background-color: #4cd964;
            border-radius: 10rpx;
            color: #fff;
        }
       
    }
    .colors{
        display: flex;
        justify-content: space-around;
        margin: 10px;
        .color-item{
            width: 20px;
            height: 20px;
            border-radius: 50%;
            border: 2px solid #000;
        }
    }
</style>
